<template>
  <div :class="['filewheel', customClass]" title="点击下载" @click="downloadFile">
    <i class="el-icon-document file-icon" />
    <span class="fileName" :title="fileName">{{ fileName }}</span>
  </div>
</template>
<script>
export default {
  inheritAttrs: false,
  props: {
    fileName: {
      type: String,
      default: '无'
    },
    url: {
      type: String,
      required: true
    },
    customClass: {
      type: String,
      default: ''
    }
  },
  methods: {
    downloadFile() {
      const loading = this.$loading({
        lock: true,
        text: '文件下载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // 浏览器支持fetch则用blob下载，避免浏览器点击a标签，跳转到新页面预览的行为
      if (window.fetch) {
        fetch(this.url)
          .then(res => res.blob())
          .then(blob => {
            const a = document.createElement('a')
            const url = window.URL.createObjectURL(blob)
            a.href = url
            a.download = this.fileName
            a.click()
            window.URL.revokeObjectURL(url)
            loading.close()
          }).catch(() => {
            loading.close()
            this.$message({
              message: '文件下载失败',
              type: 'warning',
              showClose: true
            })
          })
      } else {
        const a = document.createElement('a')
        a.href = this.url
        a.target = '_blank'
        a.download = this.filename
        a.click()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.filewheel {
  min-width: 100px;
  min-height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10px;
  background: #fff;
  border-radius: 5px;
  cursor: pointer;
}
.file-icon {
  font-size: 40px !important;
}
.fileName {
  font-size: 14px;
  color: #333;
}
</style>
